package com.cy.cy2025.activity

import android.annotation.SuppressLint
import android.icu.text.SimpleDateFormat
import android.os.Build
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import com.cy.cy2025.databinding.ActivityLocationManagerTestBinding
import com.cy.cy2025.util.CoordinateUtils
import com.cy.cy2025.util.LocationManagerUtil
import com.cy.cy2025.util.LogUtil
import kotlinx.coroutines.launch

class LocationManagerTestActivity : AppCompatActivity() {

    val binding by lazy {
        ActivityLocationManagerTestBinding.inflate(layoutInflater)
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    @SuppressLint("SetTextI18n", "SimpleDateFormat")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        LocationManagerUtil.location.observe(this) {
            it?.let {
                val time = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(it.time).toString()
                val coordinate = CoordinateUtils.wgs84ToGcj02(it.latitude, it.longitude)
                binding.tvLocation.text = "定位时间：$time , \n维度：${it.latitude}, \n经度：${it.longitude} \n(${it.provider})"+"\n高德坐标：" +
                        "\n维度：${coordinate.latitude}, \n经度：${coordinate.longitude}"
                LogUtil.s("定位信息", "定位时间：$time , \n维度：${it.latitude}, \n经度：${it.longitude} \n(${it.provider})"+"\n高德坐标：" +
                        "\n维度：${coordinate.latitude}, \n经度：${coordinate.longitude}")
                lifecycleScope.launch {
                    LocationManagerUtil.getAddressFromLocation(it.latitude, it.longitude).getOrNull(0)?.let {
                        binding.tvAddress.text = "地址：$it"
                    }
                }
            }
        }

        LocationManagerUtil.startLocationUpdates()
        lifecycleScope.launch {
            LocationManagerUtil.getLocationFromAddress("湖南省益阳市赫山区沧水铺镇瑞幸咖啡").getOrNull(0)?.let {
                LogUtil.s("定位信息", "地址：${it.latitude},${it.longitude},${it.getAddressLine(0)}")
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        LocationManagerUtil.stopLocationUpdates()
    }
}